package br.brpv.silvestrin.vendas.webservice;

import java.util.ArrayList;
import java.util.StringTokenizer;

import android.content.Context;
import android.widget.Toast;
import br.brpv.silvestrin.vendas.R;
import br.brpv.silvestrin.vendas.domain.*;
import br.brpv.silvestrin.vendas.listeners.*;
import br.brpv.silvestrin.vendas.loginactivity.LoginActivity;
import br.brpv.silvestrin.vendas.mainactivity.MainActivity;
import br.brpv.silvestrin.vendas.mainactivity.SavedOrdersFragment;
import br.brpv.silvestrin.vendas.util.Compression;

import br.brpv.silvestrin.vendas.util.Encryption;
import org.ksoap2.serialization.SoapObject;

public class ServerConnection {
    // O caractere de quebra de linha da tabela retornada pelo settings_webservice
    public final static char ROW_BREAK_CHARACTER = (char) 30;
    // O caractere de quebra de coluna da tabela retornada pelo settings_webservice
    public final static char COLUMN_BREAK_CHARACTER = (char) 31;

    public static void setParameters(String url, String user, String password) {
        WebService.setURL(url);
        WebService.setUser(user);
        WebService.setPassword(password);
    }

    public static void performAddItemToOrder(Order order, AddedItem item, MakeOrderQueryListener makeOrderQueryListener) {
        Context context = makeOrderQueryListener.getActivity();
        WebService webService = new WebService(context,"",
                new addItemToOrderListener(makeOrderQueryListener));
        try {
            String wlParametros = "" +
                    "p_tpmnt|varchar|" + item.getTpmnt() + "||^" +
                    "p_id|number|" + item.getId() + "||^" +
                    "p_pedv_id|number|" + order.getId() + "||^" +
                    "p_tcom_item_id|number|" + item.getvItcomid() + "||^" +
                    "p_tmasc_item_id|number|" + item.getCodItem()+ "||^" +
                    "p_qtde|number|" + item.getAmount() + "||^" +
                    "p_vlr_bruto|number|" + item.getTotalBruto() + "||^" +
                    "p_vlr_liq|number|" + item.getTotalLiquido() + "||^" +
                    "p_unid_med_id|number|" +item.getUniMedidaId() + "||^" +
                    "p_unid_med_desc|varchar|" + item.getUniMedidaDescr() + "||^" +
                    "p_descricao|varchar|" + item.getDescription() + "||^" +
                    "p_obs|varchar|" + item.getObs() + "||^" +
                    "p_tp_desc|varchar|" + item.getTypeDiscount() + "||^" +
                    "p_vlr_desc|number|" + item.getValueDiscount() + "||^" +
                    "p_cod_lote|varchar|" + "||^" +
                    "p_prc_unit|number|" + item.getPrice() + "||";
            webService.execute(WebService.Method.F_GET_VALOR_PACKAGE, "f3i_col_silvestrin.prc_mnt_pedv_item", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class addItemToOrderListener implements WSRequestCompleteListener<SoapObject> {
        MakeOrderQueryListener caller;
        public addItemToOrderListener(MakeOrderQueryListener makeOrderQueryListener) {
            caller = makeOrderQueryListener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            String resultString = result.getProperty(0).toString();

            String str = resultString;
            System.out.println(resultString);
            ArrayList<String> tokens = new ArrayList<String>();

            while(str.indexOf('^') != -1) {
                tokens.add(str.substring(0, str.indexOf('^')));
                str = str.substring(str.indexOf('^') + 1);
            }
            tokens.add(str);

            caller.OnWebServiceAddItemReturn(tokens.get(2));
        }
    }

    private static String createOrderParameters(Order order) {
        String wlParametros = "" +
                "p_tpmnt|varchar|" + order.getTpmnt() + "||^" +
                "p_id|number|" + order.getId() + "||^" +
                "p_empr_id|number|" + order.getCompanyId() + "||^" +
                "p_cli_id|number|" + order.getClientId() + "||^" +
                "p_dt_entrega|date|" + order.getDateDeliver() + "||^" +
                "p_status|varchar|" + order.getStatus() + "||^" +
                "p_usu_id|number|" + order.getUserId() + "||^" +
                "p_tp_desc|varchar|" + order.getTypeDiscount() + "||^" +
                "p_vlr_desc|number|" + order.getValueDiscount() + "||^" +
                "p_tp_acresc|varchar|" + order.getTypeAcresc() + "||^" +
                "p_vlr_acresc|number|" + order.getValueAcresc() + "||^" +
                "p_forn_id|number|" + order.getForn_id() + "||^" +
                "p_tp_frete|varchar|" + order.getTypeFrete() + "||^" +
                "p_vlr_frete|number|" + order.getValueFrete() + "||^" +
                "p_obs_ped|varchar|" + order.getObsOrder() + "||^" +
                "p_obs_nf|varchar|" + order.getObsNotaFiscal() + "||^" +
                "p_por_id|number|" + order.getPor_id() + "||^" +
                "p_cdpg_id|number|" + order.getCondPaymentId() + "||^" +
                "p_placa|varchar|" + order.getPlaca() + "||^" +
                "p_tpnf_id|number|" + order.getTypeNotaFiscal() + "||^" +
                "p_hora_ent_inicial|varchar|" + order.getHourInicial() + "||^" +
                "p_hora_ent_final|varchar|" + order.getHourFinal() + "||^" +
                "p_estfat_id|number|" + order.getEstablishmentId() + "||^" +
                "p_rep_id|number|" + order.getRepresentanteId() + "||^" +
                "p_ordem_cpr|varchar|" + order.getOrdemCompra() + "||^" +
                "p_tprven_id|number|" + order.getPriceTableId() + "||^" +
                "p_mot_id|number|" + order.getDriverId() + "||^" +
                "p_dt_expedicao|date|" + order.getDateExped() + "||^" +
                "p_hr_expedicao|varchar|" + order.getHourExped() + "||^" +
                "p_end_id|number|" + order.getAddressId() + "||^" +
                "p_leva_lote|number|" + order.getLevaLote() + "||^" +
                "p_placa_id|number|" + order.getPlacaId() + "||^" +
                "p_cnpj_cpf|number|" + order.getCPF() + "||^" +
                "p_nome|varchar|" + order.getName() + "||" ;

        return wlParametros;
    }

    private static String getResponseNumber(String response){
        ArrayList<String> tokens = new ArrayList<String>();
            while(response.indexOf('^') != -1) {
                tokens.add(response.substring(0, response.indexOf('^')));
                response = response.substring(response.indexOf('^') + 1);
            }
            tokens.add(response);
        if(tokens.size() >= 3) return tokens.get(2);
        else return "";
    }

    public static void performMakeOrder(Order order, MakeOrderQueryListener makeOrderQueryListener) {
        Context context = makeOrderQueryListener.getActivity();
        WebService webService = new WebService(context,
                context.getString(R.string.wsmessage_make_order),
                new performMakeOrderListener(makeOrderQueryListener));

        try {
            String wlParametros = createOrderParameters(order);

            System.out.println(wlParametros);
            webService.execute(WebService.Method.F_GET_VALOR_PACKAGE, "f3i_col_silvestrin.prc_mnt_pedv", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static class performMakeOrderListener implements WSRequestCompleteListener<SoapObject> {
        MakeOrderQueryListener caller;
        public performMakeOrderListener(MakeOrderQueryListener makeOrderQueryListener) {
            caller = makeOrderQueryListener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if(result == null) caller.failedOnMakeOrder("");
            else {
                String resultString = result.getProperty(0).toString();

                if(!resultString.equalsIgnoreCase("anyType{}")) {
                   caller.OnWebServiceMakeOrderReturn(Integer.parseInt(getResponseNumber(resultString)));
                } else {
                    resultString = result.getProperty(1).toString();
                    caller.failedOnMakeOrder(resultString);
                }
            }
        }

    }

    public static void initializeOrder(Order order, MakeOrderQueryListener makeOrderQueryListener) {
        Context context = makeOrderQueryListener.getActivity();
        WebService webService = new WebService(context,
                "",
                new initializeOrderListener(makeOrderQueryListener));

        try {
            String wlParametros = createOrderParameters(order);

            System.out.println(wlParametros);
            webService.execute(WebService.Method.F_GET_VALOR_PACKAGE, "f3i_col_silvestrin.prc_mnt_pedv", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static class initializeOrderListener implements WSRequestCompleteListener<SoapObject> {
        MakeOrderQueryListener caller;
        public initializeOrderListener(MakeOrderQueryListener makeOrderQueryListener) {
            caller = makeOrderQueryListener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if(result == null) caller.failedOnInitializeOrder("");
            else {
                String resultString = result.getProperty(0).toString();

                if(!resultString.equalsIgnoreCase("anyType{}")) {
                    caller.OnWebServiceInitializeOrderReturn(Integer.parseInt(getResponseNumber(resultString)));
                } else {
                    resultString = result.getProperty(1).toString();
                    caller.failedOnInitializeOrder(resultString);
                }
            }
        }

    }

    public static void getCompanyParamsDefault(String companyId, CompanyParamsDefaultQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getCompanyParamsListener(listener));

        try {
            String wlParametros = "" +
                    "p_empresa|number|"+ companyId + "||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "pkg_sil_parametros.prc_seleciona_parametros", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getCompanyParamsListener implements WSRequestCompleteListener<SoapObject> {
        CompanyParamsDefaultQueryListener caller;
        public getCompanyParamsListener(CompanyParamsDefaultQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if(result == null) {
                caller.failedOnRetrieveCompanyParamsDefault();
                return;
            } else {
            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString, Character.toString(ROW_BREAK_CHARACTER));
            //pula primeira linha

            row.nextToken();
            if(!row.hasMoreTokens()) caller.OnWebServiceCompanyParamsDefaultReturn(null);
            else {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                caller.OnWebServiceCompanyParamsDefaultReturn(new CompanyParameters(tokens.get(0), tokens.get(1),
                        tokens.get(2), tokens.get(3), tokens.get(4), tokens.get(5), tokens.get(6), tokens.get(7),
                        tokens.get(8)));
            }
            }
        }
    }

    public static void getDefaultCompany(MainActivity mainActivity, String userId) {
        WebService ws = new WebService(mainActivity, mainActivity.getString(R.string.wsmessage_getCompaniesList),
                new getDefaultCompanyListener(mainActivity));

        try {
            String wlParametros = "" +
                    "p_usuarioid|number|"+ new Integer(userId) + "||";

            ws.execute(WebService.Method.F_GET_VALOR_PACKAGE, "pkg_sil_usu_empr_default.prc_retorna_empresa_default", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getDefaultCompanyListener implements WSRequestCompleteListener<SoapObject> {
        MainActivity caller;

        public getDefaultCompanyListener(MainActivity mainActivity) {
            caller = mainActivity;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if(result == null) {
                //TODO avisar que nao conseguiu acessar o servidor
                caller.onGetDefaultCompanyError();
            } else {

                String resultString = result.getProperty(0).toString();

                caller.onGetDefaultCompanyResult(resultString);
            }

        }
    }

    public static void getCompaniesList(MainActivity mainActivity) {
        WebService ws = new WebService(mainActivity, mainActivity.getString(R.string.wsmessage_getCompaniesList),
                new getCompaniesListListener(mainActivity));

        try {
            String wlParametros = "" +
                    "p_filtro|varchar|||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_empresas", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getCompaniesListListener implements WSRequestCompleteListener<SoapObject> {
        MainActivity caller;

        public getCompaniesListListener(MainActivity mainActivity) {
            caller = mainActivity;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if(result == null) {
                //TODO avisar que nao conseguiu acessar o servidor
                caller.onGetCompaniesListError();
            } else {

                String resultString = Compression.decompress(result.getProperty(0).toString());
                StringTokenizer row = new StringTokenizer(resultString, Character.toString(ServerConnection.ROW_BREAK_CHARACTER));
                ArrayList<Company> companyArrayList = new ArrayList<Company>();
                //pula primeira linha
                if(row.countTokens() != 0){
                row.nextToken();
                while(row.hasMoreTokens()) {

                    ArrayList<String> tokens = new ArrayList<String>();
                    String str = row.nextToken();

                    while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                        tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                        str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                    }
                    tokens.add(str);

                    companyArrayList.add(new Company(tokens.get(0), tokens.get(1), tokens.get(2), tokens.get(3)));
                }
                }
                caller.onGetCompaniesListResult(companyArrayList);
            }
        }
    }

    public static void selectUser(String user, String password, LoginActivity loginActivity) {

        WebService ws = new WebService(loginActivity, loginActivity.getString(R.string.wsmessage_selectinguser),
                new selectUserListener(loginActivity));

        try {
            String wlParametros = "" +
                    "p_nome|varchar|" + user.toUpperCase() + "||" +
                    "^p_senha|varchar|"+ Encryption.encrypt(password) +"||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "pkg_ger_usuarios.prc_seleciona_usuario", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class selectUserListener implements WSRequestCompleteListener<SoapObject> {
        private LoginActivity caller;

        public selectUserListener(LoginActivity caller) {
            super();
            this.caller = caller;
        }

        public void onTaskComplete(SoapObject result) {
            if(result == null) {
                //TODO avisar que nao conseguiu acessar o servidor
                caller.onSelectUserServerError();
            } else {
                System.out.println(result.getProperty(0).toString());
                String resultString = Compression.decompress(result.getProperty(0).toString());
                System.out.println(resultString);
                StringTokenizer row = new StringTokenizer(resultString, Character.toString(ServerConnection.ROW_BREAK_CHARACTER));


                try {
                    //pula primeira linha
                    row.nextToken();
                    ArrayList<String> tokens = new ArrayList<String>();
                    String str = row.nextToken();

                    while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                        tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                        str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                    }
                    tokens.add(str);

                    caller.onSelectUser(new User(tokens.get(2), tokens.get(4)));
                } catch (Exception e) {
                    caller.onSelectUser(null);
                }
            }
        }
    }

    public static void validateUser(String user, String password, ValidateWSListener caller) {
        WebService ws = new WebService(caller.getActivity(), caller.getActivity().getString(R.string.wsmessage_validateuser),
                new validateUserListener(caller));

        try{
            ws.execute(WebService.Method.VALIDA_USUARIO, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class validateUserListener implements WSRequestCompleteListener<SoapObject> {
        private ValidateWSListener caller;

        public validateUserListener(ValidateWSListener caller) {
            super();
            this.caller = caller;
        }

        public void onTaskComplete(SoapObject result) {
            if(result == null) {
                //TODO avisar que nao conseguiu acessar o servidor
            }

            boolean valid = false;

            if(result != null) valid = result.getProperty(0).toString().equals("true");

            caller.onValidateUser(valid);
        }

    }

    public static void getDefaultEstablishment(int codEmp, String clientId, EstablishmentQueryListener listener) {
    	WebService ws = new WebService(listener.getActivity(), listener.getActivity().getString(R.string.wsmessage_getdefaultestablishments),
                new getDefaultEstablishmentListener(listener));

        String wlParametros = "" +
                "p_empr_id|number|" + codEmp +"||" +
                "^p_cli_id|number|" + clientId + "||" +
                "^p_tipo|varchar|" + "D" + "||" +
                "^p_filtro|varchar|" + "" + "||";

        try {
            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_est_cli", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getDefaultEstablishmentListener implements WSRequestCompleteListener<SoapObject> {
        private EstablishmentQueryListener caller;

        public getDefaultEstablishmentListener(EstablishmentQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveEstablishment();
                return;
            }

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString, Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            // descarta a primeira linha, que contem o nome das
            // colunas da tabela
            row.nextToken();

            // enquanto ainda existem linhas na tabela
            ArrayList<String> tokens = new ArrayList<String>();
            if(row.hasMoreTokens()){
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                Establishment estab = new Establishment(tokens.get(0), tokens.get(1), tokens.get(2), tokens.get(3),
                        tokens.get(4), tokens.get(5), tokens.get(6), tokens.get(7), tokens.get(8), tokens.get(9), tokens.get(10), tokens.get(11));
                caller.OnWebServiceDefaultEstablishmentReturn(estab);
            }

        }

    }
    
    public static void getEstablishments(int codEmp, String clientId, EstablishmentQueryListener listener) {
        WebService ws = new WebService(listener.getActivity(), listener.getActivity().getString(R.string.wsmessage_getestablishments),
                new getEstablishmentsListener(listener));

        String wlParametros = "" +
                "p_empr_id|number|" + codEmp +"||" +
                "^p_cli_id|number|" + clientId + "||" +
                "^p_tipo|varchar|" + "T" + "||" +
                "^p_filtro|varchar|" + "" + "||";

        try {
            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_est_cli", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getEstablishmentsListener implements WSRequestCompleteListener<SoapObject> {
        private EstablishmentQueryListener caller;

        public getEstablishmentsListener(EstablishmentQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveEstablishment();
                return;
            }

            ArrayList<Establishment> estabs = new ArrayList<Establishment>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString, Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            // descarta a primeira linha, que contem o nome das
            // colunas da tabela
            row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                Establishment estab = new Establishment(tokens.get(0), tokens.get(1), tokens.get(2), tokens.get(3),
                        tokens.get(4), tokens.get(5), tokens.get(6), tokens.get(7), tokens.get(8), tokens.get(9), tokens.get(10), tokens.get(11));
                estabs.add(estab);
            }

            ArrayList<ItemCfg> items = new ArrayList<ItemCfg>();
            caller.OnWebServiceEstablishmentReturn(estabs);
        }

    }

    public static void getItemsCfg(int codEmp, String codItem, String codPriceTable, boolean itemsInStock,
                                   ItemsQueryListener listener) {
        WebService ws = new WebService(listener.getActivity(), listener.getActivity().getString(R.string.wsmessage_getitemsconf),
                new getItemsCfgListener(listener));

        String wlFiltro = "";
        if (itemsInStock)
            wlFiltro += " and (focco3i_estoque.retorna_saldo(e.id,ite.id,almox.COD_ALMOX,sysdate,'NAO',mi.id) > 0)";
        else
            wlFiltro += "";

        String wlParametros = "" +
                "p_empr_id|number|" + codEmp+ "||^" +
                "p_itcom_id|number|" + codItem + "||^" +
                "p_prven_id|number|" + codPriceTable + "||^" + //tabela de precos
                "p_filtro|varchar|" + wlFiltro + "||^" +
                "p_num_linha_i|number|" + 0 + "||^" +
                "p_num_linha_f|number|" + 99999 + "||";
        try {
            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_itens_cfg", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getItemsCfgListener implements WSRequestCompleteListener<SoapObject> {
        private ItemsQueryListener caller;

        public getItemsCfgListener(ItemsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveItemsCfg();
                return;
            }

            ArrayList<ItemCfg> items = new ArrayList<ItemCfg>();
            String resultString = Compression.decompress(result.getProperty(0).toString());
            System.out.println(resultString);
            StringTokenizer row = new StringTokenizer(resultString, Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            // descarta a primeira linha, que contem o nome das
            // colunas da tabela
            row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                if(tokens.size() == 17) {
                    ItemCfg item = new ItemCfg(tokens.get(0), tokens.get(1), tokens.get(2), tokens.get(3),
                            tokens.get(4), tokens.get(5), tokens.get(6), tokens.get(7), tokens.get(8), tokens.get(9), tokens.get(10), tokens.get(11),
                            tokens.get(12), tokens.get(13), tokens.get(14), tokens.get(15), tokens.get(16));
                    items.add(item);
                }
            }

            caller.OnWebServiceItemsCfgReturn(items);
        }
    }

    public static void getNoStockSaleItems(int codEmp, String codItem, String codPriceTable, boolean itemsInStock,
                                           ItemsQueryListener listener) {
        WebService ws = new WebService(listener.getActivity(), listener.getActivity().getString(R.string.wsmessage_getitemsconf_nostocksale),
                new getNoStockSaleItemListener(listener));

        String wlFiltro = "";
        if (itemsInStock)
            wlFiltro += " and " +
                    " exists (select cod_masc_item from fullsoft.sil_produtos p where p.empr_id = e.id and p.cod_masc_item = mi.id)";
        else
            wlFiltro += "";

        String wlParametros = "" +
                "p_empr_id|number|" + codEmp+ "||^" +
                "p_itcom_id|number|" + codItem + "||^" +
                "p_prven_id|number|" + codPriceTable + "||^" + //tabela de precos
                "p_filtro|varchar|" + wlFiltro + "||^" +
                "p_num_linha_i|number|" + 0 + "||^" +
                "p_num_linha_f|number|" + 99999 + "||";
        try {
            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_itens_cfg", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getNoStockSaleItemListener implements WSRequestCompleteListener<SoapObject> {
        private ItemsQueryListener caller;

        public getNoStockSaleItemListener(ItemsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            try{
                ArrayList<ItemCfg> items = new ArrayList<ItemCfg>();
                System.out.println(result.getProperty(0).toString());
                String resultString = Compression.decompress(result.getProperty(0).toString());

                StringTokenizer row = new StringTokenizer(resultString, Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

                // descarta a primeira linha, que contem o nome das
                // colunas da tabela
                row.nextToken();

                // enquanto ainda existem linhas na tabela
                while (row.hasMoreTokens()) {
                    ArrayList<String> tokens = new ArrayList<String>();
                    String str = row.nextToken();

                    while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                        tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                        str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                    }
                    tokens.add(str);

                    if(tokens.size() == 17) {
                        ItemCfg item = new ItemCfg(tokens.get(0), tokens.get(1), tokens.get(2), tokens.get(3),
                                tokens.get(4), tokens.get(5), tokens.get(6), tokens.get(7), tokens.get(8), tokens.get(9), tokens.get(10), tokens.get(11),
                                tokens.get(12), tokens.get(13), tokens.get(14), tokens.get(15), tokens.get(16));
                        item.setAllowNoStockSale(true);
                        items.add(item);
                    }
                }

                caller.OnWebServiceNoStockSaleItemsReturn(items);
            } catch (Exception e) {
                e.printStackTrace();
                caller.failedOnRetrieveItemsNoStockSale();
            }
        }
    }

    public static void getItemCfgStock(String codEmp, String codItem, String codItemCfg,
                                       ItemConvertUMListener listener) {
        WebService ws = new WebService(listener.getActivity(), null,
                new getItemCfgStockListener(listener));

        String wlFiltro = "";

        wlFiltro += " and  mi.id = " + codItemCfg;


        String wlParametros = "" +
                "p_empr_id|number|" + codEmp+ "||^" +
                "p_itcom_id|number|" + codItem + "||^" +
                "p_prven_id|number|" + 2012 + "||^" + //tabela de precos
                "p_filtro|varchar|" + wlFiltro + "||^" +
                "p_num_linha_i|number|" + 0 + "||^" +
                "p_num_linha_f|number|" + 99999 + "||";
        try {
            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_itens_cfg", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getItemCfgStockListener implements WSRequestCompleteListener<SoapObject> {
        private ItemConvertUMListener caller;

        public getItemCfgStockListener(ItemConvertUMListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveStock();
                return;
            }

            ArrayList<ItemCfg> items = new ArrayList<ItemCfg>();
            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString, Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            // descarta a primeira linha, que contem o nome das
            // colunas da tabela
            row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                if(tokens.size() == 17) {
                    ItemCfg item = new ItemCfg(tokens.get(0), tokens.get(1), tokens.get(2), tokens.get(3),
                            tokens.get(4), tokens.get(5), tokens.get(6), tokens.get(7), tokens.get(8), tokens.get(9), tokens.get(10), tokens.get(11),
                            tokens.get(12), tokens.get(13), tokens.get(14), tokens.get(15), tokens.get(16));
                    item.setAllowNoStockSale(true);
                    items.add(item);
                }
            }

            if(items.isEmpty()) caller.failedOnRetrieveStock();
            else caller.OnWebServiceItemCfgStockReturn(items.get(0).getQtdeEstoque());
        }
    }


    public static void getItems(int codEmp, ItemsQueryListener listener) {
        if(listener != null) {
        WebService ws = new WebService(listener.getActivity(), listener.getActivity().getString(R.string.wsmessage_getitems),
                new getItemsListener(listener));

        String wlParametros = "" +
                "p_empr_id|number|" + codEmp +"||" +
                "^p_filtro|varchar|" + "" + "||";

        try {
            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_itens_com", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
        }
    }

    private static class getItemsListener implements WSRequestCompleteListener<SoapObject>{
        private ItemsQueryListener caller;

        public getItemsListener(ItemsQueryListener caller) {
            this.caller = caller;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveItems();
                return;
            }

            ArrayList<Item> items = new ArrayList<Item>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString, Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            // descarta a primeira linha, que contem o nome das
            // colunas da tabela
            if(row.countTokens() != 0){
            row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                Item item = new Item(tokens.get(0), tokens.get(1), tokens.get(2));
                items.add(item);
            }
            }
            caller.OnWebServiceItemsReturn(items);
        }
    }

	/**
	 * @param codEmp
	 * 			o código da empresa da qual serão buscados os clientes
	 * @param clientsQueryListener
	 * 			listener para o callback do WebService
	 */
    public static void getClients(int codEmp, ClientsQueryListener clientsQueryListener) {
        Context context = clientsQueryListener.getActivity();
        WebService ws = new WebService(context, context.getString(R.string.wsmessage_getclient),
                new getClientsListener(clientsQueryListener));

        try {
            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_clientes", "p_empr_id|number|" + codEmp + "||^p_filtro|varchar|||" );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getClientsListener implements WSRequestCompleteListener<SoapObject> {
        private ClientsQueryListener caller;

        public getClientsListener(ClientsQueryListener clientsQueryListener) {
            super();
            this.caller = clientsQueryListener;
        }

        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveClients();
                return;
            }

            ArrayList<Client> clients = new ArrayList<Client>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString, Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            // descarta a primeira linha, que contem o nome das
            // colunas da tabela
            row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);
                if(tokens.size() == 3) {
                    Client client = new Client(tokens.get(0), tokens.get(1), tokens.get(2));
                    clients.add(client);
                }
            }

            caller.OnWebServiceClientsReturn(clients);
        }
    }

    /**
     * @param url
     * @param caller
     */
    public static void validateServer(String url, ValidateWSListener caller) {
        // TODO mudar mensagem
        WebService ws = new WebService(caller.getActivity(), caller.getActivity().getString(R.string.wsmessage_validateserver),
                new validateServerListener(caller));
        WebService.setURL(url);

        try{
            ws.execute(WebService.Method.HELLO_WORLD, "Hello");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class validateServerListener implements WSRequestCompleteListener<SoapObject> {
        private ValidateWSListener caller;

        public validateServerListener(ValidateWSListener caller) {
            super();
            this.caller = caller;
        }

        public void onTaskComplete(SoapObject result) {
            if(result != null)
                caller.onValidateServer(true);
                //TODO testar getProperty(string)
            else caller.onValidateServer(false);
        }

    }

    public static void getCompanyTransportation(int companyId, CompanyParamsQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getCompanyTransportationListener(listener));

        try {
            String wlParametros = "" +
                    "p_empr_id|number|"+ companyId + "||" +
                    "^p_filtro|varchar|||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_transp", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getCompanyTransportationListener implements WSRequestCompleteListener<SoapObject> {
        CompanyParamsQueryListener caller;
        public getCompanyTransportationListener(CompanyParamsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveTransportation();
                return;
            }
            ArrayList<Transportation> transportations = new ArrayList<Transportation>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString, Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            // descarta a primeira linha, que contem o nome das
            // colunas da tabela
            row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                Transportation transportation = new Transportation(tokens.get(0), tokens.get(1), tokens.get(2));
                transportations.add(transportation);
            }
            caller.OnWebServiceCompanyTransportationReturn(transportations);

        }
    }

    public static void getCompanyCondPayment(int companyId, CompanyParamsQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getCompanyCondPaymentListener(listener));

        try {
            String wlParametros = "" +
                    "p_empr_id|number|"+ companyId + "||" +
                    "^p_filtro|varchar|||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_condpgto", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getCompanyCondPaymentListener implements WSRequestCompleteListener<SoapObject> {
        CompanyParamsQueryListener caller;
        public getCompanyCondPaymentListener(CompanyParamsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrievePaymentForm();
                return;
            }
            ArrayList<PaymentForm> paymentFormArrayList = new ArrayList<PaymentForm>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString,
                    Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            // descarta a primeira linha, que contem o nome das
            // colunas da tabela
            if(row.countTokens() != 0){
                row.nextToken();

                // enquanto ainda existem linhas na tabela
                while (row.hasMoreTokens()) {
                    ArrayList<String> tokens = new ArrayList<String>();
                    String str = row.nextToken();

                    while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                        tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                        str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                    }
                    tokens.add(str);

                    PaymentForm paymentForm = new PaymentForm(tokens.get(0), tokens.get(1), tokens.get(2),tokens.get(3),
                            tokens.get(4));
                    paymentFormArrayList.add(paymentForm);
                }
            }
            caller.OnWebServiceCompanyPaymentFormReturn(paymentFormArrayList);

        }
    }

    public static void getPortadores(CompanyParamsQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getPortadoresListener(listener));

        try {
            String wlParametros = "" +
                    "p_filtro|varchar|||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_portadores", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getPortadoresListener implements WSRequestCompleteListener<SoapObject> {
        CompanyParamsQueryListener caller;
        public getPortadoresListener(CompanyParamsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveBanks();
                return;
            }
            ArrayList<Bank> bankArrayList = new ArrayList<Bank>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString,
                    Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            // descarta a primeira linha, que contem o nome das
            // colunas da tabela
            row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                Bank bank = new Bank(tokens.get(0), tokens.get(1), tokens.get(2));
                bankArrayList.add(bank);
            }
            caller.OnWebServiceBanksReturn(bankArrayList);

        }
    }

    public static void getCompanyInvoiceType(int companyId, CompanyParamsQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getCompanyInvoiceTypeListener(listener));

        try {
            String wlParametros = "" +
                    "p_empr_id|number|"+ companyId + "||" +
                    "^p_filtro|varchar|||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_tpnf", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getCompanyInvoiceTypeListener implements WSRequestCompleteListener<SoapObject> {
        CompanyParamsQueryListener caller;
        public getCompanyInvoiceTypeListener(CompanyParamsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveInvoiceType();
                return;
            }
            ArrayList<Invoice> invoiceArrayList = new ArrayList<Invoice>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString,
                    Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            // descarta a primeira linha, que contem o nome das
            // colunas da tabela
            row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                Invoice invoice = new Invoice(tokens.get(0), tokens.get(1), tokens.get(2));
                invoiceArrayList.add(invoice);
            }
            caller.OnWebServiceInvoiceTypeReturn(invoiceArrayList);

        }
    }

    public static void getCompanyVendors(int companyId, CompanyParamsQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getCompanyRepresentantesListener(listener));

        try {
            String wlParametros = "" +
                    "p_codempresa|number|"+ companyId + "||" +
                    "^p_filtro|varchar|||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_representantes", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getCompanyRepresentantesListener implements WSRequestCompleteListener<SoapObject> {
        CompanyParamsQueryListener caller;
        public getCompanyRepresentantesListener(CompanyParamsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetriveVendors();
                return;
            }

            ArrayList<Vendor> vendorArrayList = new ArrayList<Vendor>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString,
                    Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

             row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                Vendor vendor = new Vendor(tokens.get(0), tokens.get(1), tokens.get(2));
                vendorArrayList.add(vendor);
            }
            caller.OnWebServiceVendorsReturn(vendorArrayList);

        }
    }

    public static void getMotorists(CompanyParamsQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getMotoristsListener(listener));

        try {
            String wlParametros = "" +
                    "p_filtro|varchar|||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_motoristas", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getMotoristsListener implements WSRequestCompleteListener<SoapObject> {
        CompanyParamsQueryListener caller;
        public getMotoristsListener(CompanyParamsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetriveMotorists();
                return;
            }

            ArrayList<Motorist> motoristArrayList = new ArrayList<Motorist>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString,
                    Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                Motorist motorist = new Motorist(tokens.get(0), tokens.get(1), tokens.get(2));
                motoristArrayList.add(motorist);
            }
            caller.OnWebServiceMotoristsReturn(motoristArrayList);

        }
    }

    public static void getCompanyPriceTable(int companyId, CompanyParamsDefaultQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getCompanyPriceTableListener(listener));

        try {
            String wlParametros = "" +
                    "p_codemp|number|"+ companyId + "||" +
                    "^p_filtro|varchar|||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_tab_precos", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getCompanyPriceTableListener implements WSRequestCompleteListener<SoapObject> {
        CompanyParamsDefaultQueryListener caller;
        public getCompanyPriceTableListener(CompanyParamsDefaultQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrivePriceTables();
                return;
            }

            ArrayList<PriceTable> priceTables = new ArrayList<PriceTable>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString,
                    Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                PriceTable priceTable = new PriceTable(tokens.get(0), tokens.get(1), tokens.get(2));
                priceTables.add(priceTable);
            }
            caller.OnWebServicePriceTablesReturn(priceTables);

        }
    }

    public static void getClientPlacas(String clientId, ClientsQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getClientPlacasListener(listener));

        try {
            String wlParametros = "" +
                    "p_clienteid|number|"+clientId+"||" +
                    "^p_filtro|varchar|||";

            ws.execute(WebService.Method.F_GET_PACKAGE,
                    "pkg_sil_cliente_placa.prc_listagem_placas_cliente", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getClientPlacasListener implements WSRequestCompleteListener<SoapObject> {
        ClientsQueryListener caller;
        public getClientPlacasListener(ClientsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveClientPlacas();
                return;
            }

            ArrayList<Placa> placas = new ArrayList<Placa>();

            String resultString = Compression.decompress(result.getProperty(0).toString());
            System.out.println(resultString);

            StringTokenizer row = new StringTokenizer(resultString,
                    Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                Placa placa = new Placa(tokens.get(0), tokens.get(1));
                placas.add(placa);
            }
            caller.OnWebServiceClientPlacasReturn(placas);
        }
    }

    public static void setClientPlaca(String clientId, String placa, ClientsQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new setClientPlacaListener(listener));

        try {
            String wlParametros = "" +
                    "p_clienteid|number|"+clientId+"||" +
                    "|^p_placa|varchar|" + placa + "||";
            System.out.println(wlParametros);
            ws.execute(WebService.Method.F_GET_VALOR_PACKAGE,
                    "pkg_sil_placa.prc_cadastrar_placa", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class setClientPlacaListener implements WSRequestCompleteListener<SoapObject> {
        ClientsQueryListener caller;
        public setClientPlacaListener(ClientsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnSetClientPlaca();
                return;
            }

            String resultString = result.getProperty(0).toString();
            System.out.println("Retorna placa");
            caller.OnWebServiceSetClientPlacaReturn(resultString);
        }
    }

    public static void setClientAddress(String clientId, String address, ClientsQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new setClientAddressListener(listener));

        try {
            String wlParametros = "" +
                    "p_clienteid|number|"+clientId+"||" +
                    "|^p_endereco|varchar|" + address + "||";
            System.out.println(wlParametros);
            ws.execute(WebService.Method.F_GET_VALOR_PACKAGE,
                    "pkg_sil_endereco_entrega.prc_cadastrar_endereco", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class setClientAddressListener implements WSRequestCompleteListener<SoapObject> {
        ClientsQueryListener caller;
        public setClientAddressListener(ClientsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnSetClientAddress();
                return;
            }

            String resultString = result.getProperty(0).toString();
            System.out.println("Retorna Endereco");
            caller.OnWebServiceSetClientAddressReturn(resultString);
        }
    }

    public static void getClientAddress(String clientId, ClientsQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getClientAddressListener(listener));

        try {
            String wlParametros = "" +
                    "p_clienteid|number|"+clientId+"||" +
                    "^p_filtro|varchar|||";

            ws.execute(WebService.Method.F_GET_PACKAGE,
                    "pkg_sil_cliente_endereco.prc_listagem_enderecos_cliente", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getClientAddressListener implements WSRequestCompleteListener<SoapObject> {
        ClientsQueryListener caller;
        public getClientAddressListener(ClientsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveClientAddress();
                return;
            }

            ArrayList<Address> addresses = new ArrayList<Address>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString,
                    Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            row.nextToken();

            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                Address address = new Address(tokens.get(0), tokens.get(1));
                addresses.add(address);
            }

            caller.OnWebServiceClientAddressReturn(addresses);
        }
    }

    public static void getOrderValorBruto(String orderId, MakeOrderQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getOrderValorBrutoListener(listener));

        try {
            String wlParametros = "" +
                    "p_pdv_id|number|"+ orderId +"|||";

            ws.execute(WebService.Method.F_GET_VALOR_PACKAGE,
                    "f3i_col_silvestrin.prc_busca_vlr_bruto_pedv", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getOrderValorBrutoListener implements WSRequestCompleteListener<SoapObject> {
        MakeOrderQueryListener caller;
        public getOrderValorBrutoListener(MakeOrderQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetriveValorBruto();
                return;
            }

            String resultString = result.getProperty(0).toString().replace(",",".");

            caller.OnWebServiceValorBrutoReturn(resultString);

        }
    }

    public static void getOrderValorLiquido(String orderId, MakeOrderQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getOrderValorLiquidoListener(listener));

        try {
            String wlParametros = "" +
                    "p_pdv_id|number|"+ orderId +"|||";

            ws.execute(WebService.Method.F_GET_VALOR_PACKAGE,
                    "f3i_col_silvestrin.prc_busca_vlr_liq_pedv", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getOrderValorLiquidoListener implements WSRequestCompleteListener<SoapObject> {
        MakeOrderQueryListener caller;
        public getOrderValorLiquidoListener(MakeOrderQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetriveValorLiquido();
                return;
            }

            String resultString = result.getProperty(0).toString().replace(",",".");

            caller.OnWebServiceValorLiquidoReturn(resultString);

        }
    }

    public static void finalizeOrder(String orderId, String status, MakeOrderQueryListener makeOrderQueryListener) {
        WebService ws = new WebService(makeOrderQueryListener.getActivity(),
                makeOrderQueryListener.getActivity().getString(R.string.wsmessage_make_order),
                new finalizeOrderListener(makeOrderQueryListener));

        try {
            String wlParametros = "" +
                    "p_pdv_id|number|" + orderId + "||"+
                    "^p_status|number|" + status + "||";

            ws.execute(WebService.Method.F_GET_VALOR_PACKAGE, "f3i_col_silvestrin.prc_finaliza_pedv", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class finalizeOrderListener implements WSRequestCompleteListener<SoapObject> {
        private MakeOrderQueryListener caller;

        public finalizeOrderListener(MakeOrderQueryListener makeOrderQueryListener) {
            caller = makeOrderQueryListener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnFinalizeOrder();
                return;
            }

            String resultString = result.getProperty(0).toString();
            System.out.println(resultString);

            if(!resultString.equalsIgnoreCase("anyType{}")) {
                caller.OnWebServiceFinalizeOrderReturn(resultString);
            } else {
                caller.failedOnFinalizeOrder();
            }

        }

    }

    public static void getClientDefaultParams(int companyId, String clientId, String establishmentId,
                                              ClientParamsDefaultQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getClientDefaultParamsListener(listener));

        try {
            String wlParametros = "" +
                    "p_empr_id|number|" + companyId + "||" +
                    "^p_cli_id|number|" + clientId + "||" +
                    "^p_est_id|number|" + establishmentId + "||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_default", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getClientDefaultParamsListener implements WSRequestCompleteListener<SoapObject> {
        private ClientParamsDefaultQueryListener caller;

        public getClientDefaultParamsListener(ClientParamsDefaultQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnEstabDefaultParams();
                return;
            }
            String resultString = Compression.decompress(result.getProperty(0).toString());
            System.out.println(resultString);


            StringTokenizer row = new StringTokenizer(resultString,
                    Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            row.nextToken();

            // enquanto ainda existem linhas na tabela
            if (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                EstabParamsDefault estabParamsDefault = new EstabParamsDefault(tokens.get(0), tokens.get(1),
                        tokens.get(2), tokens.get(3), tokens.get(4), tokens.get(5));

                caller.OnWebServiceEstabDefaultParamsReturn(estabParamsDefault);
            }


        }
    }

    // --------------------  SavedOrdersFragment begin

	/**
	 * @param clientId
	 * 			o id do cliente do qual os pedidos serão buscados. 0 busca pedidos de todos os clientes
	 * @param codEmp
	 * 			o código da empresa na qual serão buscados os pedidos salvos
	 * @param userId
	 * 			o id do usuário (vendedor) que fez o pedido
	 * @param listener
	 * 			listener para o callback do WebService
	 */
    public static void getSavedOrders(int clientId, int userId, int codEmp, SavedOrdersFragment listener) {
        WebService ws = new WebService(listener.getActivity(), listener.getActivity().getString(R.string.wsmessage_getsavedorders),
                new getSavedOrdersListener(listener));
        
        String wlParametros = "" +
                "p_cli_id|number|" + clientId +"||" +
                "^p_usu_id|number|" + userId + "||" +
                "^p_filtro|varchar|AND pdv.empr_id = " + codEmp + "||";
        
        try {
            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_pedv", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getSavedOrdersListener implements WSRequestCompleteListener<SoapObject> {
        private SavedOrdersFragment caller;

        public getSavedOrdersListener(SavedOrdersFragment listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveSavedOrders();
                return;
            }

            ArrayList<Order> ordersList = new ArrayList<Order>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString, Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            // descarta a primeira linha, que contem o nome das
            // colunas da tabela
            row.nextToken();
            
            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
            	ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                // TODO arrumar classe Order
                Order order = new Order();
                order.setTpmnt("A");
                //0 IDEMPR_IDCLI_IDDT_EMISDT_ENTREGASTATUSVLR_DESCFORN_IDTP_FRETE9VLR_FRETE
                order.setId(tokens.get(0));
                order.setCompanyId(tokens.get(1));
                order.setClientId(tokens.get(2));
                order.setDateEmiss(tokens.get(3));
                order.setDateDeliver(tokens.get(4));
                order.setStatus(tokens.get(5));
                order.setValueDiscount(tokens.get(6));
                order.setForn_id(tokens.get(7));
                order.setTypeFrete(tokens.get(8));
                order.setValueFrete(tokens.get(9));
                //10OBS_PEDOBS_NFPOR_IDCDPG_IDTPNF_IDHORA_ENT_INICIALHORA_ENT_FINALUSU_ID18EST_ID_FAT
                order.setObsOrder(tokens.get(10));
                order.setObsNotaFiscal(tokens.get(11));
                order.setPor_id(tokens.get(12));
                order.setCondPaymentId(tokens.get(13));
                order.setTypeNotaFiscal(tokens.get(14));
                order.setHourInicial(tokens.get(15));
                order.setHourFinal(tokens.get(16));
                order.setUserId(tokens.get(17));
                order.setEstablishmentId(tokens.get(18));
                //19ORDEM_CPRDT_EXPEDICAOTPRVEN_IDMOT_IDREP_IDTP_DESCTP_ACRESCVLR_ACRESC27HR_EXPEDICAO
                order.setOrdemCompra(tokens.get(19));
                order.setDateExped(tokens.get(20));
                order.setPriceTableId(tokens.get(21));
                order.setDriverId(tokens.get(22));
                order.setRepresentanteId(tokens.get(23));
                order.setTypeDiscount(tokens.get(24));
                order.setTypeAcresc(tokens.get(25));
                order.setValueAcresc(tokens.get(26));
                order.setHourExped(tokens.get(27));
                //28END_IDPDV_IDIMPRESSOLEVA_LOTEPLACA_IDNOME_CLINOME_EMPPLACA36NOME_ESTABELECIMENTO
                order.setAddressId(tokens.get(28));
                order.setPdv_id(tokens.get(29));
                order.setImpresso(tokens.get(30));
                order.setLevaLote(tokens.get(31));
                order.setPlacaId(tokens.get(32));
                order.setNomeCli(tokens.get(33));
                order.setNomeEmp(tokens.get(34));
                order.setPlaca(tokens.get(35));
                order.setNomeEstab(tokens.get(36));
                

                ordersList.add(order);
            }

            caller.OnWebServiceSavedOrdersReturn(ordersList);
        }

    }

	/**
	 * @param orderId
	 * 			o id do pedido do qual se quer buscar os itens
	 * @param itemId
	 * 			o id do item do pedido. 0 para buscar todos os itens
	 * @param listener
	 * 			listener para o callback do WebService
	 */
    public static void getItemsFromSavedOrder(int orderId, int itemId, SavedOrdersFragment listener) {
        WebService ws = new WebService(listener.getActivity(), listener.getActivity().getString(R.string.wsmessage_getitemsfromsavedorder),
                new getItemsFromSavedOrderListener(listener));
        
        String wlParametros = "" +
                "p_pdv_id|number|" + orderId +"||" +
                "^p_pdvitem_id|number|" + itemId + "||";
        
        try {
            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_pedv_item", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static class getItemsFromSavedOrderListener implements WSRequestCompleteListener<SoapObject> {
        private SavedOrdersFragment caller;

        public getItemsFromSavedOrderListener(SavedOrdersFragment listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRetrieveItemsFromSavedOrder();
                return;
            }

            ArrayList<AddedItem> itemsList = new ArrayList<AddedItem>();

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString, Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            // descarta a primeira linha, que contem o nome das
            // colunas da tabela
            row.nextToken();
            
            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
            	ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();
                
                System.out.println(str);

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);
                
                AddedItem item = new AddedItem();
                
                // TODO arrumar classe AddedItem
                //0 IDPEDV_IDTMASC_ITEM_IDQTDEVLR_BRUTOVLR_LIQUNID_MED_IDDESCRICAO OBS
                //UNID_MED_DESCTCOM_ITEM_IDVLR_DESCTP_DESCPRC_UNITTAXA_CONV ITEMID_FOCCO
                //COD_LOTECOD_TELA55709411764078800306060246KIWI NACIONAL PAP 17KGCX306130P215
                item.setTpmnt("A");
                item.setId(tokens.get(0));
                item.setOrderId(tokens.get(1));
                item.setCodItem(tokens.get(2));
                item.setAmount(Integer.valueOf(tokens.get(3)));
                item.setValorBruto(tokens.get(4).replace(',', '.'));
                item.setValorLiquido(tokens.get(5).replace(',', '.'));
                item.setUniMedidaId(tokens.get(6));
                item.setDescription(tokens.get(7));
                item.setObs(tokens.get(8));
                item.setUniMedidaDescr(tokens.get(9));
                item.setvItcomid(tokens.get(10));
                item.setValueDiscount(Float.valueOf(tokens.get(11).replace(',', '.')));
                item.setTypeDiscount(tokens.get(12));
                item.setPrice(Float.valueOf(tokens.get(13).replace(',', '.')));
                
                itemsList.add(item);
            }

            caller.OnWebServiceItemsFromSavedOrderReturn(itemsList);
        }

    }

    public static void performRemoveItemFromOrder(String itemId, MakeOrderQueryListener makeOrderQueryListener) {
        Context context = makeOrderQueryListener.getActivity();
        WebService webService = new WebService(context,"",
                new removeItemFromOrderListener(makeOrderQueryListener));
        try {
            String wlParametros = "" +
                    "p_id|number|"+itemId+"||";

            webService.execute(WebService.Method.F_GET_VALOR_PACKAGE, "f3i_col_silvestrin.prc_excluir_pedv_item", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class removeItemFromOrderListener implements WSRequestCompleteListener<SoapObject> {
        MakeOrderQueryListener caller;
        public removeItemFromOrderListener(MakeOrderQueryListener makeOrderQueryListener) {
            caller = makeOrderQueryListener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            String resultString = result.getProperty(0).toString();

            String str = resultString;
            ArrayList<String> tokens = new ArrayList<String>();

            while(str.indexOf('^') != -1) {
                tokens.add(str.substring(0, str.indexOf('^')));
                str = str.substring(str.indexOf('^') + 1);
            }
            tokens.add(str);

            System.out.println(tokens.get(2));
            caller.OnWebServiceRemoveItemReturn(tokens.get(2));
        }
    }

    
    // --------------------  SavedOrdersFragment end


    public static void getClientTitcr(int companyId, String clientId, String establishmentId,
                                      ClientParamsDefaultQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getClientTitcrListener(listener));

        try {
            String wlParametros = "" +
                    "p_empr_id|number|" + companyId + "||" +
                    "^p_cli_id|number|" + clientId + "||" +
                    "^p_est_id_fat|number|" + establishmentId + "||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_titcr", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getClientTitcrListener implements WSRequestCompleteListener<SoapObject> {
        private ClientParamsDefaultQueryListener caller;

        public getClientTitcrListener(ClientParamsDefaultQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnEstabDefaultParams();
                return;
            }

            String resultString = Compression.decompress(result.getProperty(0).toString());

            StringTokenizer row = new StringTokenizer(resultString,
                    Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            row.nextToken();
            ArrayList<PaymentLate> paymentLateArrayList = new ArrayList<PaymentLate>();
            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                PaymentLate paymentLate = new PaymentLate(tokens.get(0), tokens.get(1),
                        tokens.get(2), tokens.get(3), tokens.get(4), tokens.get(5), tokens.get(6));
                paymentLateArrayList.add(paymentLate);
                System.out.println(tokens);

            }
            caller.OnWebServicePaymentLateReturn(paymentLateArrayList);

        }
    }

    public static void getItemPrice(int companyId, String codItem, String priceTableId, String codItemCfg, String clientId, String estabId, ItemsQueryListener listener) {
        Context context = listener.getActivity();
        WebService ws = new WebService(context,
                "",
                new getItemPriceListener(listener));

        try {
            String wlParametros = "" +
                    "pi_empr_id|number|" + companyId + "||" +
                    "^pi_itcm_id|number|" + codItem + "||" +
                    "^pi_tprven_id|number|" + priceTableId + "||" +
                    "^pi_tmasc_item_id|number|" + codItemCfg + "||" +
                    "^pi_cli_id|number|" + clientId + "||" +
                    "^pi_est_id|number|" + estabId + "||";

            ws.execute(WebService.Method.F_GET_VALOR_PACKAGE,
                    "f3i_col_silvestrin.prc_busca_preco_pol", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getItemPriceListener implements WSRequestCompleteListener<SoapObject> {
        ItemsQueryListener caller;
        public getItemPriceListener(ItemsQueryListener listener) {
            caller = listener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnItemCfgValue();
                return;
            }

            String resultString = result.getProperty(0).toString().replace(",",".");
            if(resultString.equalsIgnoreCase("anyType{}")) {
                Toast.makeText(caller.getActivity(), result.getProperty(1).toString(), Toast.LENGTH_LONG).show();
                resultString = "0";
            }
            caller.OnWebServiceItemPriceReturn(resultString);

        }
    }

    public static void removeOrder(String orderId, MakeOrderQueryListener makeOrderQueryListener) {
        WebService ws = new WebService(makeOrderQueryListener.getActivity(),
                makeOrderQueryListener.getActivity().getString(R.string.wsmessage_remove_order),
                new removeOrderListener(makeOrderQueryListener));

        try {
            String wlParametros = "" +
                    "p_id|number|" + orderId + "||";

            ws.execute(WebService.Method.F_GET_VALOR_PACKAGE, "f3i_col_silvestrin.prc_excluir_pedv", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class removeOrderListener implements WSRequestCompleteListener<SoapObject> {
        private MakeOrderQueryListener caller;

        public removeOrderListener(MakeOrderQueryListener makeOrderQueryListener) {
            caller = makeOrderQueryListener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnRemoveOrder();
                return;
            }

            String resultString = result.getProperty(0).toString();
            System.out.println(resultString);

            if(!resultString.equalsIgnoreCase("anyType{}")) {
                caller.OnWebServiceRemoveOrderReturn(resultString);
            } else {
                caller.failedOnRemoveOrder();
            }

        }

    }

    public static void getUnitsOfMeasurement(int companyId, CompanyParamsDefaultQueryListener companyParamsDefaultQueryListener) {
        WebService ws = new WebService(companyParamsDefaultQueryListener.getActivity(),
                "",
                new getUnitsOfMeasurementListener(companyParamsDefaultQueryListener));

        try {
            String wlParametros = "" +
                    "p_empr_id|number|" + companyId + "||^p_filtro|varchar|||";

            ws.execute(WebService.Method.F_GET_PACKAGE, "f3i_col_silvestrin.prc_busca_um", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class getUnitsOfMeasurementListener implements WSRequestCompleteListener<SoapObject> {
        private CompanyParamsDefaultQueryListener caller;

        public getUnitsOfMeasurementListener(CompanyParamsDefaultQueryListener companyParamsDefaultQueryListener) {
            caller = companyParamsDefaultQueryListener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedGetUnitsOfMeasurement();
                return;
            }

            String resultString = Compression.decompress(result.getProperty(0).toString());
            System.out.println("Unidade medida = " + resultString);
            StringTokenizer row = new StringTokenizer(resultString,
                    Character.toString(ServerConnection.ROW_BREAK_CHARACTER));

            row.nextToken();
            ArrayList<UnitOfMeasurement> unitOfMeasurementArrayList = new ArrayList<UnitOfMeasurement>();
            // enquanto ainda existem linhas na tabela
            while (row.hasMoreTokens()) {
                ArrayList<String> tokens = new ArrayList<String>();
                String str = row.nextToken();

                while(str.indexOf(COLUMN_BREAK_CHARACTER) != -1) {
                    tokens.add(str.substring(0, str.indexOf(COLUMN_BREAK_CHARACTER)));
                    str = str.substring(str.indexOf(COLUMN_BREAK_CHARACTER) + 1);
                }
                tokens.add(str);

                UnitOfMeasurement unitOfMeasurement = new UnitOfMeasurement(tokens.get(0), tokens.get(1),
                        tokens.get(2));
                unitOfMeasurementArrayList.add(unitOfMeasurement);
            }
            caller.OnWebServiceUnitsOfMeasurementReturn(unitOfMeasurementArrayList);
        }
    }


    public static void itemConvertUM(String companyId, AddedItem item, ItemConvertUMListener itemConvertUMListener) {
        WebService ws = new WebService(itemConvertUMListener.getActivity(),
                itemConvertUMListener.getActivity().getString(R.string.wsmessage_convert_unit_of_measurement),
                new itemConvertUMListener(itemConvertUMListener));

        try {
            String wlParametros = "" +
                    "p_empr_id|number|" + companyId +"||^" +
                    "p_itcm_id|number|" + item.getvItcomid() + "||^" +
                    "p_tmasc_item_id|number|" + item.getCodItem() + "||^" +
                    "p_unid_med_id|number|" + item.getUniMedidaId() + "||";

            ws.execute(WebService.Method.F_GET_VALOR_PACKAGE, "f3i_col_silvestrin.prc_fator_convert", wlParametros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class itemConvertUMListener implements WSRequestCompleteListener<SoapObject> {
        private ItemConvertUMListener caller;

        public itemConvertUMListener(ItemConvertUMListener itemConvertUMListener) {
            caller = itemConvertUMListener;
        }

        @Override
        public void onTaskComplete(SoapObject result) {
            if (result == null) {
                caller.failedOnGetConvertUMValue();
                return;
            }

            String resultString = result.getProperty(0).toString();
            System.out.println(resultString);

            if(!resultString.equalsIgnoreCase("anyType{}")) {
                resultString = resultString.replace(",", ".");
                caller.OnWebServiceConvertUMValueReturn(Double.parseDouble(resultString));
            } else {
                caller.failedOnGetConvertUMValue();
            }

        }

    }





}
